package com.smzd.framework.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.smzd.framework.system.domain.User;
import com.smzd.framework.system.domain.UserSecurity;

@Component
public class SmzdPasswordEncoder implements PasswordEncoder {
	static final char[] HEXCHARTABLE = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
	static MessageDigest md5;
	static{
		try {
			md5 = MessageDigest.getInstance("md5");
		} catch (NoSuchAlgorithmException e) {
			md5 = null;
			e.printStackTrace();
		}
	}
	
	@Override
	public String encodePassword(String rawPass, Object salt) {
		byte[] newPassArr = md5.digest(rawPass.getBytes());
		StringBuffer sb = new StringBuffer(32);
		for(int i=0; i<16; i++){
			byte v = newPassArr[i];
			sb.append(HEXCHARTABLE[(v&0xf0)>>4]);
			sb.append(HEXCHARTABLE[(v&0x0f)]);
		}
		return sb.toString();
	}

	@Override
	public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
		if(salt!=null){
			User user = (User) salt;
			if(UserSecurity.isUserSecurity(user)){
				return true;
			}
			String userName = user.getName();
			rawPass = rawPass+"{"+userName+"}"; 
		}
		String encoded = encodePassword(rawPass, salt);
		if (encoded.equalsIgnoreCase(encPass)) {
			return true;
		}
		return false;
	}

	public static void main(String[] args){
		String value = "这是什么";
		byte[] newPassArr = md5.digest(value.getBytes());
		System.out.println(newPassArr.length);
		for(int i=0; i<16; i++){
			byte v = newPassArr[i];
			System.out.print(HEXCHARTABLE[(v&0xf0)>>4]);
			System.out.print(HEXCHARTABLE[(v&0x0f)]);
		}
		System.out.println();
		String newValue = new String(newPassArr);
		System.out.println(newValue);
	}
}
